#include "stdafx.h"
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glut.h"
#include <time.h>
#include "Imagem.h"
#include "PCXImage.h"

Imagem *image = NULL;
int winWidth=800, winHeight=700;

void init (void){
    // Black background
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    
    // Targa's are 1 byte aligned
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	PCXImage pcxImage( "examples/example.pcx" );
	image = pcxImage.loadPCXImage( );
	/*
	image = new Imagem(500,300);
	srand((unsigned int)time(NULL));
	for(int y=0; y<image->getHeight(); y++){
		for(int x=0; x<image->getWidth(); x++){
			int r;
			int g;
			int b;
			r = rand() % 256;
			g = rand() % 256;
			b = rand() % 256;
			
			int rgb = (r << 16) | (g << 8) | b;
			image->setRGB(x, y, rgb);
		}
	}
	*/
}

void finish(void){
	if(image != NULL)
		delete(image);
}

void ChangeSize(int w, int h){
    // Janela menor que 10x10? NAH!
    if(h <= 10)
        h = 10;
	if(w <= 10)
        w = 10;

	winWidth = w;
	winHeight= h;

    glViewport(0, 0, w, h);
        
	// Reset the coordinate system before modifying
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
	
    // Set the clipping volume
    gluOrtho2D(0.0f, (GLfloat) w, 0.0, (GLfloat) h);
        
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void RenderScene(void){
    // Clear the window with current clearing color
    glClear(GL_COLOR_BUFFER_BIT);
    // Draw the pixmap
	if(image != NULL){
		// Use Window coordinates to set raster position
		glRasterPos2i(0, winHeight - image->getHeight());
		glDrawPixels(image->getWidth(), image->getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, image->getPixels());
	}
	glutSwapBuffers();
}

void keyboard (unsigned char key, int x, int y) {
	switch (key) {
		case 'Q':
		case 'q':
			finish();
			exit(0);
	}
	glutSwapBuffers();
}

int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GL_DOUBLE);
	glutInitWindowSize(winWidth, winHeight);
    glutCreateWindow("OpenGL - Desenho Imagem");

    glutReshapeFunc(ChangeSize);
    glutDisplayFunc(RenderScene);
	glutKeyboardFunc(keyboard);

	init();
	glutMainLoop();
	finish();

	return 0;
}

